package com.camps.sdk.encrypt;

import com.camps.sdk.common.ExceptionCode;
import com.camps.sdk.entity.SetSosPhone;
import com.camps.sdk.entity.SosPhone;
import com.camps.sdk.exception.BaseException;
import com.camps.sdk.utils.UnicodeUtil;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author ldaoliang
 * @Date create in 10:11 2021/9/1
 * @Description
 */
public class SetSosCommand implements BuildCommand {

    private static int sosStandardCount = 3;

    @Override
    public String splicingParameters(String imei,Object params) {
        if(!(params instanceof SetSosPhone)){
            throw new BaseException(ExceptionCode.PARAMETER_ERROR);
        }
        SetSosPhone setSosPhone = (SetSosPhone)params;
        String commandNumber = setSosPhone.getCommandNumber();
        List<SosPhone> sosPhoneList = setSosPhone.getSosPhoneList();
        StringBuilder sb = new StringBuilder("*WT,");
        sb = sb.append(imei).append(",SETSOS,").append(commandNumber);
        String phoneStr = "";
        sosPhoneList = sosPhoneList.stream().sorted(Comparator.comparingInt(SosPhone::getSequence)).collect(Collectors.toList());
        for(int i = 0 ; i < sosStandardCount ; i ++){
            if(sosPhoneList.size() >= i + 1){
                SosPhone sosPhone = sosPhoneList.get(i);
                String name = sosPhone.getName();
                String phone = sosPhone.getPhone();
                Integer sequence = sosPhone.getSequence();
                if(sequence == null){
                    throw new BaseException(ExceptionCode.SEQUENCE_CAN_NOT_NULL);
                }
                if(name != null && !"".equals(name)){
                    name = UnicodeUtil.gbEncoding(name);
                }
                sb = sb.append(",").append(sequence).append(",").append(name).append(",").append(phone);
            }else{
                sb = sb.append(",").append(i + 1).append(",,");
            }
            sb = sb.append("#");
        }
        return sb.toString();
    }
}
